# app/services/appointment_service.py
from app.models.appointment import Appointment, Provider, MOCK_PROVIDERS, MOCK_APPOINTMENTS
from datetime import datetime, date

class AppointmentService:
    @staticmethod
    def get_available_providers(date_str, time_slot, appointment_type):
        # Filter providers based on type
        available_providers = [
            provider for provider in MOCK_PROVIDERS 
            if provider.type == appointment_type
        ]
        
        # Filter out providers with existing appointments on the same date and time
        booked_providers = [
            appt.provider_id for appt in MOCK_APPOINTMENTS 
            if appt.date == date_str and appt.time_slot == time_slot
        ]
        
        available_providers = [
            provider for provider in available_providers 
            if provider.id not in booked_providers
        ]
        
        return available_providers

    @staticmethod
    def create_appointment(user_id, provider_id, date_str, time_slot, appointment_type):
        # Validate provider exists
        provider = next((p for p in MOCK_PROVIDERS if p.id == provider_id), None)
        if not provider:
            raise ValueError("Provider not found")
        
        # Check if provider is already booked
        existing_appointments = [
            appt for appt in MOCK_APPOINTMENTS 
            if appt.provider_id == provider_id 
            and appt.date == date_str 
            and appt.time_slot == time_slot
        ]
        if existing_appointments:
            raise ValueError("Provider is already booked for this time slot")
        
        # Create new appointment
        new_appointment = Appointment(
            user_id=user_id,
            provider_id=provider_id,
            date=date_str,
            time_slot=time_slot,
            appointment_type=appointment_type
        )
        
        MOCK_APPOINTMENTS.append(new_appointment)
        return new_appointment

    @staticmethod
    def get_user_appointments(user_id):
        return [
            appt for appt in MOCK_APPOINTMENTS 
            if appt.user_id == user_id
        ]